package jobs;

// 图片接口
interface Image {
    void display();
}

// 真实图片类
class RealImage implements Image {
    private String fileName;
    private boolean loaded = false;

    public RealImage(String fileName) {
        this.fileName = fileName;
    }

    // 模拟加载图片（耗时）
    private void load() {
        if (!loaded) {
            System.out.println("正在加载图片: " + fileName);
            try {
                Thread.sleep(2000); // 模拟耗时
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            loaded = true;
            System.out.println("图片加载完成: " + fileName);
        }
    }

    @Override
    public void display() {
        load();
        System.out.println("显示图片: " + fileName);
    }
}

// 图片代理类
class ImageProxy implements Image {
    private String fileName;
    private RealImage realImage;
    private boolean loading = false;

    public ImageProxy(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void display() {
        if (realImage == null) {
            if (!loading) {
                System.out.println("显示占位图...");
                loading = true;
                realImage = new RealImage(fileName);
            }
            realImage.display();
        } else {
            realImage.display();
        }
    }
}

// 测试类
public class ImageProxyTest {
    public static void main(String[] args) {
        Image image = new ImageProxy("test.jpg");
        System.out.println("第一次调用display:");
        image.display(); // 首次加载，先显示占位图，再加载并显示真实图片
        System.out.println("\n第二次调用display:");
        image.display(); // 已加载，直接显示真实图片
    }
}
